import { templateXml } from '@/api/template'

export const BPMN_TEMPLATE =
  `<?xml version="1.0" encoding="UTF-8"?>
  <definitions
    xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
    xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC"
    xmlns:camunda="http://camunda.org/schema/1.0/bpmn"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:activiti="http://activiti.org/bpmn"
    id="m1577635100724"
    name=""
    targetNamespace="http://www.activiti.org/testm1577635100724"
  >
  <process id="process" processType="None" isClosed="false" isExecutable="true">
    <extensionElements>
      <camunda:properties>
        <camunda:property name="a" value="1" />
      </camunda:properties>
    </extensionElements>
    <startEvent id="_2" name="start" />
  </process>
  <bpmndi:BPMNDiagram id="BPMNDiagram_leave">
    <bpmndi:BPMNPlane id="BPMNPlane_leave" bpmnElement="leave">
      <bpmndi:BPMNShape id="BPMNShape__2" bpmnElement="_2">
        <omgdc:Bounds x="144" y="368" width="32" height="32" />
        <bpmndi:BPMNLabel>
          <omgdc:Bounds x="149" y="400" width="23" height="14" />
        </bpmndi:BPMNLabel>
      </bpmndi:BPMNShape>
    </bpmndi:BPMNPlane>
  </bpmndi:BPMNDiagram>
  </definitions>
`

/**
 * 后台请求获取xml文件
 *
 * @param modelId 模型ID
 * @returns {Promise<unknown>}
 */
export async function httpTemplate(modelId) {
  return new Promise((resolve, reject) => {
    templateXml(modelId).then(response => {
      if (response.status === 200) {
        resolve(response.data)
      }
      resolve(BPMN_TEMPLATE)
    }).then(error => {
      reject(error)
    })
  })
}

export async function createDiagram(bpmn) {
  // 将字符串转换成图显示出来;
  this.bpmnModeler.importXML(bpmn, err => {
    if (err) {
      this.$message.error('打开模型出错,请确认该模型符合Bpmn2.0规范')
    }
  })
}

export function initParams() {

}

/**
 * 通过BPMN xml文件获取文件名称
 *
 * @param xml
 * @returns {string}
 */
export function getFilename(xml) {
  const start = xml.indexOf('process')
  let filename = xml.substr(start, xml.indexOf('>'))
  filename = filename.substr(filename.indexOf('id') + 4)
  filename = filename.substr(0, filename.indexOf('"'))
  return filename
}

/**
 * 下载XML格式流程图文件
 */
export function downloadXML() {
  this.bpmnModeler.saveXML({ format: true }, (err, xml) => {
    if (!err) {
      // 将文件名以及数据交给下载方法
      downloadFile({ fileName: getFilename(xml), fileType: 'bpmn', data: xml }, this)
    }
  })
}

/**
 * 下载SVG格式流程图文件
 */
export function downloadSVG() {
  this.bpmnModeler.saveXML({ format: true }, (err, xml) => {
    if (!err) {
      // 从建模器画布中提取svg图形标签
      let context = ''
      const djsGroupAll = this.$refs.canvas.querySelectorAll('.djs-group')
      for (const item of djsGroupAll) {
        context += item.innerHTML
      }
      // 获取svg的基本数据，长宽高
      const viewport = this.$refs.canvas.querySelector('.viewport').getBBox()
      // 将标签和数据拼接成一个完整正常的svg图形
      const svg = `
            <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${viewport.width}" height="${viewport.height}" viewBox="${viewport.x} ${viewport.y} ${viewport.width} ${viewport.height}" version="1.1">
              ${context}
            </svg>
          `
      // 将文件名以及数据交给下载方法
      downloadFile({ fileName: getFilename(xml), fileType: 'svg', data: svg }, this)
    }
  })
}

/**
 * 下载对应格式文件
 *
 * @param fileName
 * @param fileType
 * @param data
 */
export function downloadFile({ fileName, fileType, data }, $vue) {
  if (!fileName) {
    fileName = 'bpmn'
  }
  // 这里就获取到了之前设置的隐藏链接
  const downloadLink = $vue.$refs.downloadLink
  // 把输就转换为URI，下载要用到的
  const encodedData = encodeURIComponent(data)

  if (data) {
    // 将数据给到链接
    downloadLink.href = 'data:application/bpmn20-xml;charset=UTF-8,' + encodedData
    // 设置文件名
    downloadLink.download = `${fileName}.${fileType}`
    // 触发点击事件开始下载
    downloadLink.click()
  }
}

